package com.turing.post.cardmanagement.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.capitalaccounts.util.CapitalApplicationException;
import com.turing.post.cardmanagement.util.CardClassic;
import com.turing.post.cardmanagement.util.CardClassicDao;
import com.turing.post.cardmanagement.util.CardManaApplicationException;
import com.turing.post.cardmanagement.util.CardManaRespCode;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

@Stateless(mappedName = "cardmanagement.impl.CardClassicDaoImpl")
@Remote
@Local
public class CardClassicDaoImpl implements CardClassicDao {

	@PersistenceContext
	protected EntityManager _em;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao pcpsCommonDaoImpl;

	@Override
	public void deleteCardClassic(BigInteger CardClassicId)
			throws PCPSApplicationException {
		CardClassic cc = getCardClassicByCardClassicId(CardClassicId);
		if (cc != null) {
			GeneralDao.remove(_em, cc);
		}
	}

	@Override
	public CardClassic getCardClassicByCardClassicId(BigInteger CardClassicId) {
		return _em.find(CardClassic.class, CardClassicId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CardClassic> getCardClassicListByCondition(PCPSWebInput input,
			String allowdeposit, String isrealname, Integer page) {
		String issueCompanyNo =PCPSUtil.getIssueCompanyNo(input);
		String sql = "select * from cardclassic c where c.issuecompanyno=?1 "
				+ "and ('-1'=?2 or c.allowdeposit=?2) "
				+ "and ('-1'=?3 or c.isrealname=?3) "
				+ "order by c.cardclassicid desc";
		Query query = _em.createNativeQuery(sql, CardClassic.class);
		query.setParameter(1, issueCompanyNo);
		query.setParameter(2, allowdeposit);
		query.setParameter(3, isrealname);
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		query.setFirstResult(startPosition);
		query.setMaxResults(maxResult);
		return query.getResultList();
	}

	public Integer getCardClassicCountByIssueCompanyNo(PCPSWebInput input,
			String allowdeposit, String isrealname) {
		String issueCompanyNo = PCPSUtil.getIssueCompanyNo(input);
		String sql = "select nvl(count(*),0) from cardclassic c where c.issuecompanyno=?1 "
				+ "and ('-1'=?2 or c.allowdeposit=?2) "
				+ "and ('-1'=?3 or c.isrealname=?3) "
				+ "order by c.cardclassicid desc";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, issueCompanyNo);
		query.setParameter(2, allowdeposit);
		query.setParameter(3, isrealname);
		return Integer.parseInt(query.getSingleResult().toString());
	}

	@Override
	public void insertCardClassic(CardClassic cardClassic)
			throws PCPSApplicationException {

		if (PCPSUtil.isEmpty(cardClassic.getIssueCompanyNo()))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"机构号码为空");
		if (cardClassic.getStatus() == null
				|| (!cardClassic.getStatus().equals(
						CardClassic.CARDCLASSIC_STATUS_NORMAL) && !cardClassic
						.getStatus()
						.equals(CardClassic.CARDCLASSIC_STATUS_STOP)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"status异常");
		if (cardClassic.getIsRealName() == null
				|| (!cardClassic.getIsRealName().equals(
						CardClassic.CARDCLASSIC_STATUS_REALNAME) && !cardClassic
						.getIsRealName().equals(
								CardClassic.CARDCLASSIC_STATUS_NONAME)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"实名设置异常");
		if (cardClassic.getAllowDeposit() == null
				|| (!cardClassic.getAllowDeposit().equals(
						CardClassic.CARDCLASSIC_ALLOWDEPOSIT_RECHARGE) && !cardClassic
						.getAllowDeposit().equals(
								CardClassic.CARDCLASSIC_STATUS_NONAME)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"充值设置异常");
		if (IsCardClassicName(cardClassic.getIssueCompanyNo(), cardClassic
				.getCardClassicName(), null) > 0) {
			throw new CapitalApplicationException(
					CapitalApplicationException.ERRMSG_NULLPOINTER,
					CardManaRespCode.RC_ARGS_NULL, "种类名称:"
							+ cardClassic.getCardClassicName() + " 已经存在");
		}
		cardClassic.setCardClassicId((pcpsCommonDaoImpl.getUniqueIntegerKey()));
		GeneralDao.insert(_em, cardClassic);
	}

	@Override
	public void updateCardClassic(CardClassic CardClassic)
			throws PCPSApplicationException {
		GeneralDao.update(_em, CardClassic);
	}

	@Override
	public CardClassic getCardClassicByForUpdate(BigInteger CardClassicId) {
		String sql = "select * from CardClassic where CardClassicId="
				+ CardClassicId + " for update ";
		Query query = _em.createNativeQuery(sql, CardClassic.class);
		return (CardClassic) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CardClassic> getAllCardClassicByIssueCompanyNo(
			String issueCompanyNo) {
		String sql = "select * from cardclassic c where c.issuecompanyno=?1 and status='0' order by c.CardClassicId";
		Query query = _em.createNativeQuery(sql, CardClassic.class);
		query.setParameter(1, issueCompanyNo);
		return query.getResultList();
	}

	// @SuppressWarnings("unchecked")
	// @Override
	// public CardClassic getCardClassicByBatchNo(String batchNo) {
	// String sql =
	// "select b.* from makecardcontrol a,cardclassic b where a.cardclassicid=b.cardclassicid and a.batchno=?1";
	// if (!PCPSUtil.isEmpty(batchNo)) {
	// Query query = _em.createNativeQuery(sql, CardClassic.class);
	// query.setParameter(1, batchNo);
	// List<CardClassic> resultList = query.getResultList();
	// if (resultList.size() > 0) {
	// return resultList.get(0);
	// }
	// return null;
	// } else {
	// return null;
	// }
	// }

	@SuppressWarnings("unchecked")
	@Override
	public List<CardClassic> getCardClassicHashMap(PCPSWebInput input) {
		if (input == null || PCPSUtil.isEmpty(input.getOperBranchNo()))
			return null;
		String issueCompanyNo =PCPSUtil.getIssueCompanyNo(input);
		String sql = "select t.* from CardClassic t where IssueCompanyNo='"
				+ issueCompanyNo + "' order by CardClassicId";
		Query query = _em.createNativeQuery(sql, CardClassic.class);
		return query.getResultList();
	}

	/**
	 * 验证卡种类名称不重复
	 * 
	 * @param cardClassicName
	 *            卡种类名称
	 * @return
	 */
	public Integer IsCardClassicName(String issuecompanyno,
			String cardClassicName, BigInteger classid) {
		if (PCPSUtil.isEmpty(cardClassicName)
				|| PCPSUtil.isEmpty(issuecompanyno))
			return 1;
		String sql = "select nvl(count(*),0) from CardClassic where IssueCompanyNo=?1 and CardClassicName=?2 and ( CardClassicId != ?3 or ?3 is NULL ) ";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, issuecompanyno);
		query.setParameter(2, cardClassicName);
		query.setParameter(3, classid);
		return Integer.parseInt(query.getSingleResult().toString());
	}
	/**
	 * 根据发卡商号和明成检索
	 */
	public String getClassicId(String issuecompanyno,String cardClassicName){
		if (PCPSUtil.isEmpty(cardClassicName)
				|| PCPSUtil.isEmpty(issuecompanyno))
			return null;
		String sql = "select CardClassicId from CardClassic where IssueCompanyNo=?1 and CardClassicName=?2";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, issuecompanyno);
		query.setParameter(2, cardClassicName);
		return query.getSingleResult().toString();
	}
	/**
	 * 新增卡种类---迁移用
	 * 
	 * @param CardClassic
	 *            对象
	 * @throws PCPSApplicationException
	 */
	public String insertCardClassic_Qy(CardClassic cardClassic)
			throws PCPSApplicationException{
		if (PCPSUtil.isEmpty(cardClassic.getIssueCompanyNo()))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"机构号码为空");
		if (cardClassic.getStatus() == null
				|| (!cardClassic.getStatus().equals(
						CardClassic.CARDCLASSIC_STATUS_NORMAL) && !cardClassic
						.getStatus()
						.equals(CardClassic.CARDCLASSIC_STATUS_STOP)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"status异常");
		if (cardClassic.getIsRealName() == null
				|| (!cardClassic.getIsRealName().equals(
						CardClassic.CARDCLASSIC_STATUS_REALNAME) && !cardClassic
						.getIsRealName().equals(
								CardClassic.CARDCLASSIC_STATUS_NONAME)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"实名设置异常");
		if (cardClassic.getAllowDeposit() == null
				|| (!cardClassic.getAllowDeposit().equals(
						CardClassic.CARDCLASSIC_ALLOWDEPOSIT_RECHARGE) && !cardClassic
						.getAllowDeposit().equals(
								CardClassic.CARDCLASSIC_STATUS_NONAME)))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"充值设置异常");
		if (IsCardClassicName(cardClassic.getIssueCompanyNo(), cardClassic
				.getCardClassicName(), null) > 0) {
			throw new CapitalApplicationException(
					CapitalApplicationException.ERRMSG_NULLPOINTER,
					CardManaRespCode.RC_ARGS_NULL, "种类名称:"
							+ cardClassic.getCardClassicName() + " 已经存在");
		}
		BigInteger classid=pcpsCommonDaoImpl.getUniqueIntegerKey();
		cardClassic.setCardClassicId(classid);
		GeneralDao.insert(_em, cardClassic);
		return classid.toString();
	}
}
